# -*- conding:UTF-8 -*-

'''
@ Project: P8 flask_progect
@ File: courses.py
@ Author: 罗婷
@ Date：2022/6/23 12:01

'''
import json

from flask import Blueprint, jsonify
from flask_restful import Api, Resource, reqparse, marshal
# from sqlalchemy import and_

from common.model_fields.courses import *
from common.models.course import *
from common.utils.Search_Es.select_fields import ES

courses_bp = Blueprint('courses_bp', __name__, url_prefix='/course')

api = Api(courses_bp)

# course/get_course?page=1&size=6&tag_id=&free=&online=&sort=
class AllTag(Resource):
    def get(self):
        tags = CourseTag.query.all()
        tags_mar = marshal(tags, tags_fields)
        # print('标签====', tags_mar)
        return tags_mar

# 多判断条件 展示课程
class TagCourse(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        argss = ['tag_id', 'free', 'online', 'sort']
        for i in argss:
            parser.add_argument(i)
        args = parser.parse_args()
        tag_id = args['tag_id']
        free = args['free']
        online = args['online']
        sort = args['sort']
        print('获取到的参数^^^^^^^^', 'tag_id', tag_id, type(tag_id),'free', free, 'online', online, type(online), 'sort', sort)
        courses_mar = []
        # 标签----->课程
        if tag_id:
            # 根据标签类型获取所有课程   再进行判断
            tags = CourseTag.query.filter_by(id=tag_id).first()
            courses = tags.course
            courses_data = json.loads(json.dumps(marshal(courses, courses_fields)))
            # print('标签对象是', tags, '未判断的课程:', courses_data)

            # 类型不为空
            if free != '' and online == '':
                for i in courses_data:
                  if i['course_type'] == free:
                      courses_mar.append(i)
                print('类型 的课程====', courses_mar)


            # 是否上线不为空
            if free == '' and online != '':
                for i in courses_data:
                  if i['course_status'] == int(online):
                      courses_mar.append(i)
                # print('是否上线 的课程====', courses_mar)

            # 类型 状态 都不为空
            if free != '' and online != '':
                for i in courses_data:
                    if i['course_status'] == int(online) and i['course_type'] == free:
                        courses_mar.append(i)
                # print('类型/上线 的课程====', courses_mar)

            # 类型 状态 都为空
            if free == '' and online == '':
                for i in courses_data:
                    courses_mar.append(i)


        if tag_id == '':   #获取所有的课程
            courses = Course.query.all()
            courses_data = json.loads(json.dumps(marshal(courses, courses_fields)))
            # print('无标签的课程====', courses_data)

            # 类型不为空
            if free != '' and online == '':
                for i in courses_data:
                    if i['course_type'] == free:
                        courses_mar.append(i)
                # print('类型 的课程====', courses_mar)

            # 是否上线
            if free == '' and online != '':
                for i in courses_data:
                    if i['course_status'] == int(online):
                        courses_mar.append(i)
                # print('是否上线 的课程====', courses_mar)

            # 类型 状态 都不为空
            if free != '' and online != '':
                for i in courses_data:
                    if i['course_status'] == int(online) and i['course_type'] == free:
                        courses_mar.append(i)
                # print('类型/上线 的课程====', courses_mar)

            # 类型 状态 都为空
            if free == '' and online == '':
                for i in courses_data:
                    courses_mar.append(i)

        if sort:
            new_data = self.sort_courses(courses_mar)  # 调用最热课程的方法 对数据排序
            return new_data
        return courses_mar

    def sort_courses(self, data):
        # TODO 高阶函数 sorted
        new_data = sorted(data, key=lambda x: x['learner'], reverse=True)
        # print("热门课程>>>>>>>>>>..", new_data)
        return new_data

# 点击课程 获取单个商品信息
# res.data.course_ser 课程详情
#  res.data..section_list 小节详情
class ShowGoods(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        argss = ['cid', 'token']
        for i in argss:
            parser.add_argument(i)
        args = parser.parse_args()
        cid = args['cid']
        token = args['token']
        print('获取到的参数^^^^^^^^', 'cid', cid, 'token', token)

        # 课程详情
        course = Course.query.filter_by(id=cid).first()
        # 章节详情
        chapters = course.chapter

        # 小节   遍历章节chapters  i   sections = i.sections
        chapters_data = []
        for i in chapters:
            # 根据字段获取小节信息
            section = i.sections
            # 序列化所有小节字段
            section_data = json.loads(json.dumps(marshal(section, section_fields)))
            # 序列化 每一个遍历的 章节字段
            chapters_ser = json.loads(json.dumps(marshal(i, chapter_fields)))
            # 将所有小节放入 当前遍历的章节
            chapters_ser['section'] = section_data
            # 将添加了小节信息的章节放入章节列表
            chapters_data.append(chapters_ser)
        # 课程的具体数据
        course_data = json.loads(json.dumps(marshal(course, courses_fields)))

        # print('course_data课程', course_data)
        # print('chapters_data章节', chapters_data)
        return jsonify(message='获取课程详情数据成功', code=200, data={'course_ser': course_data, 'chapters_ser': chapters_data})

# 展示视频 /course/sectionvideo
class ShowMp4(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('sid')
        args = parser.parse_args()
        sid = args['sid']
        # print('获取到的参数章节id^^^^^^^^', 'sid', sid)

        # 先用小节id替代章节id
        sec = Sections.query.filter_by(id=sid).first()
        sec_data = marshal(sec, section_fields)
        return jsonify(message='视频获取成功', data=sec_data, code=200)

# 搜索
class Search_Course(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('q')
        args = parser.parse_args()
        q = args['q']

        # 从 es 中查询  调用封装的ES类名 传入一个表名  生成es对象  es对象 调用_search(q)方法 q是接收的字段
        es = ES("tb_course")
        # 返回查询的结果
        rest = es._search(q)
        print('rest~~~~~~~~~~~~~~~~~~~', rest)
        return jsonify(message='搜索成功', code=200, data=rest)



api.add_resource(AllTag, '/get_tag')
# 获取标签下的课程
api.add_resource(TagCourse, '/get_course')
# 点击课程 获取单个商品信息
api.add_resource(ShowGoods, '/courseinfo')
# 展示视频
api.add_resource(ShowMp4, '/sectionvideo')
# 搜索
api.add_resource(Search_Course, '/search')





